import { createRouter, createWebHashHistory } from 'vue-router'
import { RouteRecordRaw } from 'vue-router'
import { firstMenu } from '@/utils/mapToMenus'
import LocalCache from '@/utils/cache'

import main from '@/views/main/main.vue'
import About from '@/views/About/About.vue'
import Login from '@/views/Login/Index.vue'
import NotFound from '@/views/Not-Found/Not-Found.vue'
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  { path: '/Login', name: 'Login', component: Login },
  { path: '/main', name: 'main', component: main },
  { path: '/about', name: 'about', component: About },
  {
    // 匹配未定义的路由规则
    path: '/:pathMatch(.*)*',
    name: 'Not-Found',
    component: NotFound
  }
]

const router = createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
  history: createWebHashHistory(),
  routes // `routes: routes` 的缩写
})

// 导航守卫
router.beforeEach((to) => {
  const token = LocalCache.getLocalCache('token')
  // 如果不是去登录页就检查是否已经登录存在token,没有token就跳去登录页
  if (to.path !== '/login') {
    if (!token) {
      return '/login'
    }
  }
  if (to.path === '/main') {
    return firstMenu.url
  }
})

export default router
